import router from "./index";
import store from "../store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import { validEmpty } from "@/utils/validate";
NProgress.configure({ showSpinner: false });

const whiteList = ["/sign/work", "/sign/personal", "/personalCenter/myresume"]; // 白名单

router.beforeEach(async (to, from, next) => {
    // 路由加载进度条
    NProgress.start();
    document.title = to.meta.title;
    const hasToken = getToken();
    console.log(validEmpty(hasToken), "-----", hasToken);
    if (!validEmpty(hasToken)) {
        // 这里 需要设定 一个专有的 字段 用来判断 vuex 里面的数据是否 被清空
        //如果被清空了，重新调取接口获取数据
        const hasGetUserInfo = validEmpty(store.getters.user);
        if (!hasGetUserInfo) {
            next();
        } else {
            try {
                await store.dispatch(
                    "user/getSysUserInfo",
                    JSON.parse(hasToken)
                );
                next();
            } catch (error) {
                await store.dispatch("user/resetToken");
                next("/");
                NProgress.done();
            }
        }
    } else {
        /* has no token*/
        console.log(whiteList.indexOf(to.path));
        console.log(to.path);
        if (whiteList.indexOf(to.path) === -1) {
            next();
        } else {
            next("/");
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});
